package util.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.BaseUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author yangfan
 * @description 网路传输的工具类
 * @date 2018/6/22 20:05
 **/

public class HttpUtil extends BaseUtil {

	private final static Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

	/**
	 * @param url 请求的URL
	 * @return
	 */
	public static String httpGet(String url) {
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(5000);
			// 建立实际的连接
			LOGGER.info("create connect.");
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			LOGGER.info("get url response stream.");
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (Exception e) {
			LOGGER.error("something error {}", e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return null;
	}
}
